# -*- coding: utf-8 -*-
'''
@author: wangwl
@file: deploy_conf_create
@time: 2021/09/14 15:38
@desc:
'''
import os
from components.models import ConfManagement
from general.deploy.dao import deploy_event_in
from utils.views import ReturnClass
from django.db.models import Q


class DeployConfCreate():
    @staticmethod
    def get_conf_info(conf_manage_ids):
        sql_data = ConfManagement.objects.filter(Q(conf_manage_ids=conf_manage_ids) & Q(conf_manage_code="yum_file")).values()
        return list(sql_data)

    @staticmethod
    def ssh_echo_input(ssh_obj, conf_manage_ids, deploy_event_ids):
        conf_data_list  = DeployConfCreate.get_conf_info(conf_manage_ids)

        for conf_info_one in conf_data_list:
            conf_manage_path = os.path.split(conf_info_one['conf_manage_path'])
            cmd = "mkdir -p '{conf_manage_path_dir}' && echo '{conf_manage_content}' > {conf_manage_path}".format(
                conf_manage_path_dir=conf_manage_path[0],
                conf_manage_content=conf_info_one['conf_manage_content'],
                conf_manage_path=conf_info_one['conf_manage_path'])
            exe_info = ssh_obj.execcmd(cmd)

            if not ReturnClass.if_ok(exe_info):
                deploy_event_in(deploy_event_ids,
                                '文件%s[%s]生成失败(%s)' % (conf_info_one['conf_manage_nick'], conf_info_one['conf_manage_path'], exe_info['data']), '0')
                return False

            deploy_event_in(deploy_event_ids,
                            '文件%s[%s]生成成功' %(conf_info_one['conf_manage_nick'],conf_info_one['conf_manage_path']), '2')

            if conf_info_one['conf_manage_code'] == 'service_file':
                ssh_obj.execcmd("systemctl daemon-reload")

        return True

    @staticmethod
    def ssh_echo_input_template_text(ssh_obj, text, path, deploy_event_ids):
        cmd = "echo '{conf_manage_content}' > {conf_manage_path}".format(
            conf_manage_content=text,
            conf_manage_path=path)

        exe_info = ssh_obj.execcmd(cmd)

        if not ReturnClass.if_ok(exe_info):
            deploy_event_in(deploy_event_ids,
                            '文件[%s]生成失败(%s)' % (
                            path, exe_info['data']),
                            '0')
            return False

        deploy_event_in(deploy_event_ids,
                        '文件[%s]生成成功' % (path), '2')

        return True

    @staticmethod
    def save_file_ssh_put_file(ssh_obj, text, path, deploy_event_ids):
        ssh_obj.text_save_file_put_file(text, path)

        deploy_event_in(deploy_event_ids,
                            '文件[%s]生成成功' % (
                            path),
                            '1')

        return True